<template>
  <el-card class="box-card">
    <el-row :gutter="10">
      <el-col :span="2">
        <el-select
          v-model="departmentName"
          placeholder="请选择科室"
          size="medium"
          style="width: 180px"
          @change="selectDepartment"
        >
          <el-option
            v-for="item in departmentList"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-col>

      <el-col :span="6">
        <el-input v-model="name" placeholder="请输入关键词"></el-input>
      </el-col>
      <div class="btn">
        <el-button type="info" @click="clear">重置</el-button>
        <el-button type="primary" @click="selectDepartment">查询</el-button>
        <el-button type="success" @click="add">新增</el-button>
      </div>
    </el-row>
  </el-card>

  <el-card class="box-card2">
    <el-table :data="courseList" style="width: 100%">
      <el-table-column align="center" prop="id" label="序号"> </el-table-column>
      <el-table-column align="center" prop="courseName" label="课程名称">
      </el-table-column>

      <el-table-column align="center" prop="listed" label="课程状态">
      </el-table-column>

      <el-table-column align="center" prop="dockerName" label="上传医生">
      </el-table-column>

      <el-table-column align="center" prop="hospitalName" label="医院">
      </el-table-column>

      <el-table-column align="center" prop="type" label="类型">
      </el-table-column>

      <el-table-column align="center" prop="price" label="售价">
      </el-table-column>

      <el-table-column align="center" prop="count" label="观看次数">
      </el-table-column>

      <el-table-column header-align="center" align="center" label="封面">
        <template v-slot="scope">

          <img
            :src=scope.row.video
            width="100px"
            @click="handletableVideo"
          />
        </template>

      </el-table-column>

      <el-table-column label="操作" width="350" align="center">
        <template #default="{ row }">
          <div class="mybtn">

            <el-button
              plain
              type="info"
              @click="goContent(row)"
              class="smallbtn"
              >内容管理
            </el-button>


            <el-button
              plain
              type="primary"
              @click="update(row)"
              class="smallbtn"
              >修改
            </el-button>

        

            <el-button
              plain
              type="success"
              @click="grounding(row)"
              class="smallbtn"
              v-if="row.courseStatus === 1"
              >上架
            </el-button>

            <el-button
              plain
              type="warning"
              @click="off(row)"
              class="smallbtn"
              v-if="row.courseStatus === 0"
              >下架
            </el-button>

            
            <el-button plain type="danger" @click="del(row)" class="smallbtn"
              >删除
            </el-button>

          </div>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <el-pagination
      class="fenye"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[2, 4, 6, 8]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </el-card>

  <el-dialog
    title="添加课程"
    v-model="dialogFormVisible"
    @close="clear()"
    width="1800px"
  >
    <div class="ccc">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
        <el-form-item label="医院" prop="hospitalId">
          <el-select
            v-model="form.hospitalId"
            placeholder="请选择医院"
            size="medium"
            style="width: 180px"
            @change="selectDepartment"
          >
            <el-option
              v-for="item in hospitalList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="科室" prop="departmentId">
          <el-select
            v-model="form.departmentId"
            placeholder="请选择科室"
            size="medium"
            style="width: 180px"
            @change="findDockerByDepartmentId"
          >
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="医生" prop="dockerId">
          <el-select
            v-model="form.dockerId"
            placeholder="请选择医生"
            size="medium"
            style="width: 180px"
            @change="confirmDocker"
          >
            <el-option
              v-for="item in dockerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="课程名" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名"></el-input>
        </el-form-item>


        <el-form-item label="类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择类型"
            size="medium"
            style="width: 180px"
            @change="confirmStatus"
          >
            <el-option
              v-for="item in vipList"
              :key="item.id"
              :label="item.type"
              :value="item.type"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="售价" prop="price" v-if="form.type === '付费'">
          <el-input v-model="form.price"></el-input>
        </el-form-item>

        <el-form-item label="视频" prop="file">
          <el-upload
            drag="true"
            :on-progress="handleProgress"
            v-model:file-list="fileList"
            class="upload-demo"
            :http-request="uploadFile"
            :on-exceed="handleExceed"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :list-type="text"
            limit="1"
            :on-change="hanleChange"
            :before-upload="beforeUpload"
          >
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">拖拽或<em>点击</em>上传</div>
            <template #tip>
              <div class="el-upload_tip">只能上传 mp4/webm/ogg 视频文件</div>
            </template>
          </el-upload>

          <el-progress
            type="circle"
            :percentage="percentate"
            class="myprogress"
          />
        </el-form-item>

        <el-dialog v-model="dialogVisibleVideo" @close="handleClose">
          <video w-full :src="dialogVideoUrl" controls class="preview"></video>
        </el-dialog>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </div>
  </el-dialog>

  <el-dialog
    title="修改课程"
    v-model="dialogFormVisibleUpdate"
    @close="clear2()"
    width="1800px"
  >
    <div class="ccc">
      <el-form
        :model="formUpdate"
        ref="formRefUpdate"
        :rules="rulesUpdate"
        label-width="100px"
      >
        <el-form-item label="科室" prop="departmentId">
          <el-select
            v-model="formUpdate.departmentId"
            placeholder="请选择科室"
            size="medium"
            style="width: 180px"
            @change="selectDepartment2"
          >
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="课程名" prop="courseName">
          <el-input
            v-model="formUpdate.courseName"
            placeholder="请输入课程名"
          ></el-input>
        </el-form-item>

        <el-form-item label="医生" prop="dockerId">
          <el-select
            v-model="formUpdate.dockerId"
            placeholder="请选择医生"
            size="medium"
            style="width: 180px"
            @change="confirmDocker2()"
          >
            <el-option
              v-for="item in dockerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="医院" prop="hospitalName">
          <el-input
            v-model="formUpdate.hospitalName"
            disabled="true"
          ></el-input>
        </el-form-item>

        <el-form-item label="类型" prop="status">
          <el-select
            v-model="formUpdate.status"
            placeholder="请选择类型"
            size="medium"
            style="width: 180px"
            @change="confirmStatus"
          >
            <el-option
              v-for="item in vipList"
              :key="item.id"
              :label="item.type"
              :value="item.type"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="售价"
          prop="price"
          v-if="formUpdate.status === '会员'"
        >
          <el-input v-model="formUpdate.price"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="saveUpdate">确 定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { Plus, UploadFilled } from "@element-plus/icons-vue";
import axios from "axios";
import { useRouter } from "vue-router";

const router = useRouter();

const name = ref("");
const departmentName = ref("");
const departmentList = ref([]);
const pageNum = ref(1);
const pageSize = ref(2);
const total = ref("");
const courseList = ref([]);
const dialogFormVisible = ref(false);

const form = ref({
  departmentId: "",
});

const fileList = ref([]);
const  imgUrl = 'http://localhost:8080/'

const dialogVisibleVideo = ref(false); //弹框的状态
const dialogVideoUrl = ref(""); //放大后图片路径

const dockerList = ref([]);

const hospital = ref({});

const formRef = ref();

const dialogFormVisibleUpdate = ref(false);
const formUpdate = ref({});

const formRefUpdate = ref();

const dialogTabelVideo = ref(false);

const hospitalList = ref([]);

onMounted(async () => {
  const res = await axios.get("/hospital/findAll");
  hospitalList.value = res.data.data;

  const res1 = await axios.get("/department");
  departmentList.value = res1.data.data;
  getcourseList();
});

const getcourseList = async () => {
  const res2 = await axios.get(
    "/course?pageNum=" +
      pageNum.value +
      "&pageSize=" +
      pageSize.value +
      "&name=" +
      name.value +
      "&department=" +
      departmentName.value
  );
  courseList.value = res2.data.data.items;
  total.value = res2.data.data.total;
};

const handleSizeChange = async (ps) => {
  pageSize.value = ps;
  getcourseList();
};

const handleCurrentChange = async (num) => {
  pageNum.value = num;
  getcourseList();
};

const selectDepartment = async () => {
  getcourseList();
  findDockerByDepartmentId();
  const res = await axios.get(
    "/department/findByHospitalId/" + form.value.hospitalId
  );

  departmentList.value = res.data.data;
  form.value.departmentId = "";
  form.value.dockerId = "";
};

const clear = () => {
  name.value = "";
  departmentName.value = "";
  getcourseList();

  form.value = {};
  formUpdate.value = {};
  dialogFormVisible.value = false;
  dialogFormVisibleUpdate.value = false;
  formRef.value.resetFields();

  fileList.value = [];

  percentate.value = 0;
};

const clear2 = () => {
  name.value = "";
  departmentName.value = "";
  getcourseList();

  form.value = {};
  formUpdate.value = {};
  dialogFormVisible.value = false;
  dialogFormVisibleUpdate.value = false;
  formRefUpdate.value.resetFields();
};

const findDockerByDepartmentId = async () => {
  const res = await axios.get(
    "/user/findByDepartmentId?departmentId=" + form.value.departmentId
  );
  dockerList.value = res.data.data;
  form.value.dockerId = "";
};

const add = () => {
  router.push("/file?courseId=" + "");
};

const confirmDocker = async () => {
  const res = await axios.get(
    "/hospital/findByDockerId?dockerId=" + form.value.dockerId
  );
  hospital.value = res.data.data;
};

const rules = ref({
  departmentId: [{ required: true, message: "请选择科室", trigger: "blur" }],

  name: [
    { required: true, message: "请输入课程名", trigger: "blur" },
    {
      pattern: /^\S{2,10}/,
      message: "课程名长度在2-10个非空字符",
      trigger: "blur",
    },
  ],

  dockerId: [{ required: true, message: "请选择医生", trigger: "blur" }],

  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
  type: [{ required: true, message: "请选择类型", trigger: "blur" }],
  hospitalId: [{ required: true, message: "请选择类型", trigger: "blur" }],

  price: [
    { required: true, message: "请输入价格", trigger: "blur" },
    {
      pattern: /(^[\d]|^[1-9][\d]*)($|[\.][\d]{0,2}$)/,
      message: "请填写正确的金额,保留两位小数",
      trigger: "blur",
    },
  ],
  file: [{ required: true, message: "请上传视频", trigger: "blur" }],
});

const rulesUpdate = ref({
  departmentId: [{ required: true, message: "请选择科室", trigger: "blur" }],

  courseName: [
    { required: true, message: "请输入课程名", trigger: "blur" },
    {
      pattern: /^\S{2,10}/,
      message: "课程名长度在2-10个非空字符",
      trigger: "blur",
    },
  ],

  dockerId: [{ required: true, message: "请选择医生", trigger: "blur" }],

  status: [{ required: true, message: "请选择类型", trigger: "blur" }],

  price: [
    { required: true, message: "请输入价格", trigger: "blur" },
    {
      pattern: /(^[\d]|^[1-9][\d]*)($|[\.][\d]{0,2}$)/,
      message: "请填写正确的金额,保留两位小数",
      trigger: "blur",
    },
  ],
});

const vipList = ref([
  { type: "全部免费" },
  { type: "会员免费" },
  { type: "付费" },
]);

const save = async () => {
  await formRef.value.validate();
  form.value.hospitalName = hospital.value.name;
  if (form.value.type === "全部免费") {
    form.value.type = 0;
    form.value.price = 0;
  }
  if (form.value.type === "会员免费") {
    form.value.type = 1;
    form.value.price = 0;
  }
  if (form.value.type === "付费") {
    form.value.type = 2;
  }

  let fd = new FormData();

  for (let key in form.value) {
    fd.append(key, form.value[key]);
  }
  /*fd.append('file', form.value.file)*/
  const res = await axios.post("/course/add", fd);
  ElMessage.success("添加课程成功");
  clear();
};

const del = async (item) => {
  await ElMessageBox.confirm("你确认要删除该课程么", "温馨提示", {
    type: "warning",
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  });

  const res = await axios.delete("course/" + item.id);
  ElMessage.success("删除课程成功");
  clear();
};

const findDockerByDepartmentId2 = async () => {
  const res = await axios.get(
    "/user/findByDepartmentId?departmentId=" + formUpdate.value.departmentId
  );
  dockerList.value = res.data.data;
};

const selectDepartment2 = () => {
  formUpdate.value.dockerId = "";
  formUpdate.value.hospitalName = "";
  findDockerByDepartmentId2();
};

const confirmDocker2 = async () => {
  const res = await axios.get(
    "/hospital/findByDockerId?dockerId=" + formUpdate.value.dockerId
  );
  formUpdate.value.hospitalName = res.data.data.name;
};

const update = (item) => {
  /*   dialogFormVisibleUpdate.value = true
        formUpdate.value = item
        findDockerByDepartmentId2() */

  router.push("/file?courseId=" + item.id);
};

const saveUpdate = async () => {
  await formRefUpdate.value.validate();

  if (formUpdate.value.status === "免费") {
    formUpdate.value.status = formUpdate.value.price = 0;
  }

  if (formUpdate.value.status === "会员") {
    formUpdate.value.status = 1;
  }

  const res = await axios.put("/course", formUpdate.value);

  ElMessage.success("修改课程成功");

  clear();
};

/**
 * 上架
 */
const grounding = async (item) => {
  await ElMessageBox.confirm("你确认要上架该课程么", "温馨提示", {
    type: "warning",
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  });
  const res = await axios.get("/course/grounding?id=" + item.id);
  ElMessage.success(res.data.data);
  clear();
};

/**
 * 下架
 */
const off = async (item) => {
  await ElMessageBox.confirm("你确认要下架该课程么", "温馨提示", {
    type: "warning",
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  });

  const res = await axios.get("/course/off?id=" + item.id);
  ElMessage.success(res.data.data);
  clear();
};

const percentate = ref(0);

//覆盖默认上传行为
const uploadFile = (params) => {
  //缓存文件
  form.value.file = params.file;
};

//上传组件的进度改变回调
const handleProgress = (event) => {
  percentate.value = Math.floor(event);
};

/*超出限制*/
const handleExceed = () => {
  ElMessage.warning("超出最大文件数");
};

const beforeUpload = (file) => {

   //const videoMimeTypes = ['video/mp4', 'video/webm', 'video/ogg']

  let isJPG = videoMimeTypes.includes(file.type);
  //大小
  let isLT2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage.warning("只能上传 mp4/webm/ogg 视频文件");
  }

  /* if (!isLT2M) {
             ElMessage.warning('上传文件的大小不能超过2M')
         }
 */
  return isJPG;
};

//点击文件列表的钩子
const handlePreview = (file) => {
  dialogVisibleVideo.value = true;
  dialogVideoUrl.value = URL.createObjectURL(file.raw);
};

const handleRemove = () => {
  percentate.value = 0;
};

const hanleChange = async (file) => {
  if (file.status === "ready") {
    const interval = setInterval(() => {
      if (percentate.value >= 100) {
        clearInterval(interval);
        return;
      }
      percentate.value += 1; //进度条进度
    }, 2);
  }
};

const handleClose = () => {
  const element = document.querySelector(".preview");
  element.pause();
};

const handletableVideo = () => {
  dialogTabelVideo.value = true;
};



const goContent=(item)=>{

  router.push('/admin/courseContent?id='+item.id)

}





</script>

<style scoped>
.hd {
  height: 100px;
  background-color: #fff;
  margin-top: 15px;
  box-shadow: 0 -0.05333333rem 0.42666667rem 0 rgba(14, 86, 127, 0.09);
}

.box-card {
  margin-top: 15px;
}

.btn {
  margin-left: 20px;
}

.box-card2 {
  margin-top: 15px;
  height: 700px;
}

.fenye {
  margin-top: 30px;
  margin-left: 33%;
}

.ccc {
  width: 400px;

  margin: 10px auto;
  /*background-color: skyblue;*/
}

.preview {
  width: 95%;
}

.myprogress {
  margin-left: 50px;
}
</style>
